package cc.mrbird.febs.accounting.controller;

import cc.mrbird.febs.accounting.service.ISalaryService;
import cc.mrbird.febs.common.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/salary")
public class SalaryController extends BaseController {
    @Resource
    private ISalaryService salaryService;

    /*
     * @Author HBH
     * @Description word导出样例
     * @Date 2022/3/30
     **/
    @RequestMapping(value = "/exportTemplate", method = RequestMethod.GET)
    public void export(HttpServletResponse response, @RequestParam("year") String year, @RequestParam("month") String month,
                       @RequestParam("projectId") String projectId) {
        try {
            // 得到导出文档
            File outFile = salaryService.getSalaryWord(year,month,projectId);
            InputStream fin = new FileInputStream(outFile);
            //输出Word文档
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            //response.setHeader("token_status", "ok");
            // 文件名字在后端赋值，目前为单位名称，前端接收
            //response.setHeader("file_name", new Date().toString());
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
            fin.close();
            out.close();
            if (!outFile.delete()) {
                System.out.println(outFile.getName() + "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
